
import { shuffleArray } from '../../common/utils'
import { HOST } from '../../common/constant'
import { dowImg } from '../../common/method'
import { apiAutoUpdateBgDownNumber } from '../../common/api'
var dowFilePath = '';
let currentImgUrl = '';
let itemPage = {};
let isShare = false
Page({

  /**
   * 页面的初始数据
   */
  data: {
    scrollLeft: 0,
    statusBarHeight: 0,
    isLoadMore: true,
    windowWidth: 0,
    groupCurrent: 0,
    host: HOST,
    // host: 'https://localhost',
    headerGroup: [],
    nbTitle: '新标题',
    nbLoading: true,
    nbFrontColor: '#ffffff',
    nbBackgroundColor: '#000000',
    showDialog: false,
    checkUrl: '',
    listLeft: {},
    listRight: {},
    boxWidth: '',

  },
  onClickLogo() {
    console.log('点击logo')
    wx.switchTab({ url: '/pages/recomm/index'})
   
  },
  /**
   * 初始化加载数据已经加载过的不再加载
   */
  async getlistData() {
    const { groupCurrent } = this.data
    if (this.data.listLeft[groupCurrent] && this.data.listLeft[groupCurrent].length) {
      return
    }
    this.loadListData()
  },

  /**
   * 加载数据
   */
  async loadListData() {
    const { groupCurrent } = this.data
    const res = await this.getListInfo()
    const left = []
    const right = []

    res.forEach(async (item, index) => {
      const { url } = item
      item.thumb = url.replace('images/', 'images/compressed_')
      if (index % 2 === 0) {
        left.push(item)
      } else {
        right.push(item)
      }
    })

    // {0:[],1:[],2:[]}
    const _left = {
      ...this.data.listLeft
    }
    const _right = {
      ...this.data.listRight
    }

    _left[groupCurrent] = Array.isArray(_left[groupCurrent]) ? _left[groupCurrent].concat(left) : left
    _right[groupCurrent] = Array.isArray(_right[groupCurrent]) ? _right[groupCurrent].concat(right) : right

    this.setData({
      boxWidth: (this.data.windowWidth - 10) / 2 - (5 * 2),
      listLeft: _left,
      listRight: _right
    })
    return res
  },


  async itemClick(e) {

    this.getTabBar((tabbar) => {
      tabbar.setData({
        tabBarActive: false
      })
    })

    const { detail } = e
    currentImgUrl = detail
    wx.showLoading({
      title: '加载中',
      mask: true
    })
    this.setData({
      checkUrl: ''
    })
    wx.hideLoading()
    setTimeout(() => {
      this.setData({
        showDialog: true,
        checkUrl: detail
      })
    }, 500)
  },

  dialogClose() {
    this.getTabBar((tabbar) => {
      tabbar.setData({
        tabBarActive: true
      })
    })
    this.setData({
      showDialog: false
    })
  },

  getListInfo() {
    const page = itemPage[this.data.groupCurrent] || 0
    return new Promise((resolve, reject) => {
      wx.request({
        method: "GET",
        url: `${this.data.host}/background?type=${this.data.groupCurrent}&page=${page}`,
        // url: `${this.data.host}/background?type=${this.data.groupCurrent}`,
        data: {},
        header: { 'content-type': 'application/json' },
        success: (res) => {
          const { data } = res
          // shuffleArray(data) // 随机改变数组
          resolve(data)
        }
      })
    })
  },

  /**
   * 获取分组
   */
  getBackGroup() {
    return new Promise((resolve, reject) => {
      wx.request({
        method: "GET",
        url: `${this.data.host}/backgroundGroup`,
        data: {},
        header: { 'content-type': 'application/json' },
        success: (res) => {
          const { data } = res
          resolve(data)
        }
      })
    })
  },

  /**
     * 获取可下载次数
     */
  getBackgroundDownCount() {
    return new Promise((resolve, reject) => {
      wx.request({
        method: "GET",
        url: `${this.data.host}/getBackgroundDownCount`,
        data: {},
        header: { 'content-type': 'application/json' },
        success: (res) => {
          const { data } = res
          resolve(data)
        }
      })
    })
  },


  submitDownIp({ imgid }) {
    return new Promise((resolve, reject) => {
      wx.request({
        method: "POST",
        url: `${this.data.host}/submitDownIp`,
        data: {
          imgid
        },
        header: { 'content-type': 'application/json' },
        success: (res) => {
          const { data } = res
          resolve(data)
        }
      })
    })
  },

  /**
   * 设置分组
   */
  async setBackGroup() {
    const group = await this.getBackGroup()
    this.setData({
      headerGroup: group
    })
    // 初始化分页
    group.forEach((item) => {
      itemPage[item.value] = 0
    })

  },

  async dowImg() {
    if (isShare) {
      dowImg({ imgUrl: currentImgUrl })
    } else {
      wx.showToast({
        title: '请先分享才可以下载哦',
        icon: 'none',
        mask: true
      })
    }
  },

  changeSwiper(e) {
    const { detail: { current } } = e
    this.setData({
      isLoadMore: true,
      groupCurrent: current
    })
    this.getlistData()
    this.scrollLeftEvent()
  },

  scrollLeftEvent() {
    const { groupCurrent } = this.data
    const query = wx.createSelectorQuery()
    query.select('.header-nav__item.active').fields({ node: true, size: true })
      .exec((res) => {
        const [dom] = res
        let windHalf = this.data.windowWidth / 2
        let boxSumWidth = dom.width * (groupCurrent + 1)
        if (boxSumWidth > windHalf) {
          this.setData({
            scrollLeft: boxSumWidth - windHalf
          })
        }

        // console.log(groupCurrent, this.data.windowWidth)
      })

  },

  onClickNav(e) {
    const { currentTarget: { dataset } } = e
    this.setData({
      isLoadMore: true, // 可加载更多
      groupCurrent: dataset.index
    })
    // this.getlistData()
  },

  async loadMoreItem() {
    itemPage[this.data.groupCurrent]++
    if (!this.data.isLoadMore) {
      return
    }
    const res = await this.loadListData()
    if (res.length < 10) {
      this.setData({
        isLoadMore: false
      })
    }
  },

  bindscrolltolower() {
    this.loadMoreItem()
  },
  getWindowInfos() {
    const { statusBarHeight } = wx.getWindowInfo()
    this.setData({
      statusBarHeight
    })
  },
  async onLoad(options) {
    wx.showShareMenu({
      menus: ['shareAppMessage', 'shareTimeline']
    })
    const { windowWidth } = await wx.getSystemInfo()
    this.setData({
      windowWidth
    })
    this.setBackGroup()
    this.getlistData()
    this.getWindowInfos()
  },

  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    isShare = true
    apiAutoUpdateBgDownNumber({
      userId: wx.getStorageSync('userSignature')
    })
    return {
      title: '来选一张精美的壁纸吧'
    }
  }
})